package de.nak.fireDepartment.administrationAction;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.LookupDispatchActionSupport;

import de.nak.fireDepartment.actionForms.CarForm;
import de.nak.fireDepartment.exceptions.ErrorOnDeleteException;
import de.nak.fireDepartment.model.Car;
import de.nak.fireDepartment.model.Equipment;
import de.nak.fireDepartment.service.CarService;
import de.nak.fireDepartment.service.EquipmentService;
import de.nak.fireDepartment.service.ImageUploadService;
import de.nak.fireDepartment.service.LoginService;

/**
 * Actionclass that works with the Cars
 * 
 * @author Nils Bredow
 */
public class CarAction extends LookupDispatchActionSupport {

	/**
	 * This method shows the selected car into the carForm
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return actionforward
	 * @throws Exception
	 */
	public ActionForward showCar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ActionForm => CarForm
		CarForm carForm = (CarForm) form;
		CarService carService = (CarService) getWebApplicationContext().getBean("carService");
		
		// Validate the user-login
		LoginService loginService = (LoginService)getWebApplicationContext().getBean("loginService");
		if(!loginService.checkUserIsValidated()){
			return mapping.findForward("missinglogin");
		}
		
		// if no line selected display error
		if(carForm.getSelectedKey()==null){
			carForm.setErrorCode("text.selectedKey");
			return mapping.findForward("cancel");
		}
		
		// get Car
		Car car = carService.showCar(carForm.getSelectedKey());
		
		// if car has no image set default image
		if (car.getImageURL() == null || car.getImageURL().equals("")){
			car.setImageURL("/FireDepartmentManagement/images/layout/noImage.jpg");
		}
		
		// store car and data in form
		carForm.setCar(car);
		carForm.setEquipments(car.getEquipments());
		carForm.setDepartments(car.getDepartments());
		carForm.setErrorCode("");
		// Return result
		return mapping.findForward("show");
	}
	
	/**
	 * This method prepares to create a car
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return actionforward
	 * @throws Exception
	 */
	public ActionForward createCar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ActionForm => CarForm
		CarForm carForm = (CarForm) form;		
		EquipmentService equipmentService = (EquipmentService) getWebApplicationContext().getBean("equipmentService");
		
		// Validate the user-login
		LoginService loginService = (LoginService)getWebApplicationContext().getBean("loginService");
		if(!loginService.checkUserIsValidated()){
			return mapping.findForward("missinglogin");
		}
		
		// list available equipments
		Collection<Equipment> equipments = equipmentService.listEquipments();
		// create new CarObject
		Car car= new Car();
		// store values in carForm
		carForm.setCar(car);
		carForm.setEquipments(equipments);
		carForm.setSelectedEquipmentIds(new Long[equipments.size()]);
		carForm.setSelectedEquipmentNames(new LinkedList<String>());
		carForm.setErrorCode("");
		// Return result
		return mapping.findForward("create");
	}
	
	/**
	 * This method prepares to edit a car
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return actionforward
	 * @throws Exception
	 */
	public ActionForward editCar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ActionForm => CarForm
		CarForm carForm = (CarForm) form;
		CarService carService = (CarService)getWebApplicationContext().getBean("carService");
		EquipmentService equipmentService = (EquipmentService) getWebApplicationContext().getBean("equipmentService");
		
		// Validate the user-login
		LoginService loginService = (LoginService)getWebApplicationContext().getBean("loginService");
		if(!loginService.checkUserIsValidated()){
			return mapping.findForward("missinglogin");
		}
		
		// if no line selected display error
		if(carForm.getSelectedKey()==null){
			carForm.setErrorCode("text.selectedKey");
			return mapping.findForward("cancel");
		}
		
		// get available equipments
		Collection<Equipment> equipments = equipmentService.listEquipments();
		// get selected car
		Car car = carService.showCar(carForm.getSelectedKey());
		// get equipments of selected car
		Collection<Equipment> equipmentsOfCar = car.getEquipments();
		
		//Iterate over all Cars to get the Cars of the Department for the selectionlist
		int i = 0;
		Long[] selectedEquipmentIds = new Long[equipments.size()];
		Collection <String> selectedEquipmentNames = new LinkedList<String>();
		for (Equipment equipment : equipments) {
			for (Equipment equipmentOfCar : equipmentsOfCar) {
				if(equipment.equals(equipmentOfCar)){
					selectedEquipmentIds[i] = equipment.getEquipmentId();				
					selectedEquipmentNames.add(equipment.getModelName());
					i++;
				}
			}
		}
		
		// store values in carForm
		carForm.setSelectedEquipmentIds(selectedEquipmentIds);
		carForm.setSelectedEquipmentNames(selectedEquipmentNames);
		carForm.setCar(car);
		carForm.setEquipments(equipments);
		carForm.setErrorCode("");
		// Return result
		return mapping.findForward("edit");
	}
	
	/**
	 * This method deletes the selected car
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return actionforward
	 * @throws Exception
	 */
	public ActionForward deleteCar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ActionForm => CarForm
		CarForm carForm = (CarForm) form;
		CarService carService = (CarService)getWebApplicationContext().getBean("carService");
		ImageUploadService imageUploadService = (ImageUploadService)getWebApplicationContext().getBean("imageUploadService");
		
		// Validate the user-login
		LoginService loginService = (LoginService)getWebApplicationContext().getBean("loginService");
		if(!loginService.checkUserIsValidated()){
			return mapping.findForward("missinglogin");
		}
		
		// if no line selected display error
		if(carForm.getSelectedKey()==null){
			carForm.setErrorCode("text.selectedKey");
			return mapping.findForward("cancel");
		}
		
		// get the selected car
		Car car = carService.showCar(carForm.getSelectedKey());
		String imageURL = car.getImageURL();
		try{
			// delete the car
			carService.deleteCar(carForm.getSelectedKey());
			// delete the linked image of the car
			imageUploadService.deleteImage(imageURL, getServletContext());
			// get the available list of cars and store values in form
			carForm.setCars(carService.listCars());
			carForm.setErrorCode("");
		}catch(ErrorOnDeleteException ex){
			carForm.setErrorCode(ex.getMessage());
		}
		// Return result
		return mapping.findForward("success");
	}

	
	/** {@inheritDoc} */
	@Override
	protected Map<String, String> getKeyMethodMap() {
		Map<String, String> map = new HashMap<String, String>();
		map.put("button.show", "showCar");
		map.put("button.create", "createCar");
		map.put("button.edit", "editCar");
		map.put("button.delete", "deleteCar");
		return map;
	}
}
